package com.yj.lcj.weather.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yj.lcj.weather.response.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 天气服务
 */
@Service
@Slf4j
public class WeatherService {

    @Autowired
    private RestTemplate restTemplate;


    // 第三方接口
    private final static String URL = "https://iweather.market.alicloudapi.com/address?needday={needday}&prov={prov}&city={city}&area={area}";

    private final static String APPCODE = "a06a7a7f7e194019a917d4a843a4877e";





    /**
     * 返回天气状况
     * @param needday 1 代表实时天气
     * @param prov 省份
     * @param city 城市
     * @return
     */
    public String getRealTimeWeather(String needday,String prov, String city,String area) throws IOException {

        log.info("开始调用三方接口");
        Map<String,Object> param = new HashMap<>();
        param.put("needday",needday);
        param.put("prov",prov);
        param.put("city",city);
        param.put("area",area);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization","APPCODE "+APPCODE);
//        httpHeaders.set("Authorization","APPCODE "+APPCODE);
        HttpEntity entity = new HttpEntity(httpHeaders);

        // 调用exchange方法发送请求 获取响应实体
        ResponseEntity<String> responseEntity = restTemplate.exchange(URL, HttpMethod.GET,entity,String.class,param);
        log.info("responseEntity="+responseEntity);
        // 获取请求的body
        String body = responseEntity.getBody();

        return body;
    }
}
